package com.rzrk.centerlogserver.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import com.rzrk.centerlog.entity.NormalLog;

public class BaseService<T> {
	private Class<T> entityClass;
	
	@Resource
	MongoOperations mongoOperations;

	
	public BaseService() {
		try {
			Type type = getClass().getGenericSuperclass();
			Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
			entityClass = (Class<T>) parameterizedType[0];
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public Page<T> query(Query query, Pageable pageable) {
		query.skip(0).limit(Integer.MAX_VALUE);
		long total = mongoOperations.count(query, entityClass);
		int start = pageable.getOffset();
		int size = pageable.getPageSize();
		query.skip(start).limit(size);
		List<T> resList= mongoOperations.find(query, entityClass);
		Page<T> page  = new PageImpl<T>(resList, pageable, total);
		return page;
	}

}
